<template>
  <view class="search">
    <view class="form">
      <input
        type="text"
        placeholder="请输入您要搜索的商品"
        @input="handleInput"
      />
    </view>
    <view v-if="goodsList" class="goodsList">
      <view v-for="item in goodsList" :key="item.goods_id" class="goods"
        >👉&nbsp;&nbsp;&nbsp; {{ item.goods_name }}</view
      >
    </view>
  </view>
</template>

<script>
let timeId = -1;
export default {
  data() {
    return {
      title: "Hello",
      goodsList: null,
    };
  },
  onLoad() {},
  methods: {
    handleInput(e) {
      //  输入内容 console.log(e.target.value);
      if (e.target.value.trim()) {
        // 防抖功能: 清除上次(无论是否到时)定时器达到防抖效果优化=>不用发送太多请求
        clearTimeout(timeId);
        timeId = setTimeout(() => {
          // 调用发送商品列表搜索请求
          this.getList(e.target.value);
        }, 1000);
      } else {
        this.goodsList = [];
      }
    },

    // 商品列表搜索
    async getList(query) {
      const goodsData = await uni.request({
        url: "https://api-hmugo-web.itheima.net/api/public/v1/goods/search",
        data: {
          query,
        },
      });

      this.goodsList = goodsData[1].data.message.goods;
    },
  },
};
</script>

<style lang="scss">
body {
  padding: 20rpx;
  background-color: #dedede;
  input {
    padding: 0 20rpx;
    height: 60rpx;
    background-color: #fff;
    margin-bottom: 30rpx;
  }
  .goodsList {
    .goods {
      padding: 15rpx;
      background-color: #fff;
      border-bottom: 1rpx solid #ddd;
      overflow: hidden;
      white-space: nowrap;
      text-overflow: ellipsis;
    }
  }
}
</style>
